package com.qys.livesMall.anchor.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qys.livesMall.anchor.event.UserGradeIntegralEvent;
import com.qys.livesMall.anchor.event.pojo.UserGradeIntegralPOJO;
import com.qys.livesMall.anchor.model.entity.AnchorLivesGift;
import com.qys.livesMall.anchor.model.entity.AnchorLivesGiftRecord;
import com.qys.livesMall.anchor.mapper.AnchorLivesGiftRecordMapper;
import com.qys.livesMall.anchor.model.entity.H2Anchor;
import com.qys.livesMall.anchor.model.pojo.LivesGiftRecordPOJO;
import com.qys.livesMall.anchor.service.AnchorLivesGiftRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.entity.UserRewardConfig;
import com.qys.livesMall.app.user.model.entity.UserRewardHistory;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.app.user.service.UserRewardConfigService;
import com.qys.livesMall.app.user.service.UserRewardHistoryService;
import com.qys.livesMall.cache.utils.CacheUtils;
import com.qys.livesMall.finance.common.FinanceLockPrefix;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * <p>
 * 直播礼物记录表 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-06-21
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AnchorLivesGiftRecordServiceImpl extends ServiceImpl<AnchorLivesGiftRecordMapper, AnchorLivesGiftRecord> implements AnchorLivesGiftRecordService {

    private final IH2AppUserService userService;
    private final H2AnchorService anchorService;
    private final ApplicationContext applicationContext;
    @Resource
    private UserRewardConfigService userRewardConfigService;
    @Resource
    private UserRewardHistoryService userRewardHistoryService;
    @Resource
    private CacheUtils cacheUtils;

    @Override
    public boolean createRecord(LivesGiftRecordPOJO pojo) {
        // 判断参数
        if (null == pojo.getUserId()
                || null == pojo.getLivesGift()
                || null == pojo.getQuantity()
                || null == pojo.getToAnchorId()
                || null == pojo.getLivesRoomId()
                || null == pojo.getLivesSessionId()) {
            log.error("参数异常{}", JSON.toJSON(pojo));
            return false;
        }
        if (pojo.getQuantity()<=0){
            log.error("参数异常-{},赠送数量不能低于1", pojo.getQuantity());
            return false;
        }
        H2AppUser user = userService.getById(pojo.getUserId());
        if (null == user) {
            log.error("参数异常-{},找到不到用户", pojo.getUserId());
            return false;
        }
        H2Anchor anchor = anchorService.getById(pojo.getToAnchorId());
        if (null == anchor) {
            log.error("参数异常-{},找到不到赠送主播", pojo.getToAnchorId());
            return false;
        }

        AnchorLivesGiftRecord record = new AnchorLivesGiftRecord();
        AnchorLivesGift livesGift = pojo.getLivesGift();
        record.setGiftGold(livesGift.getGiftGold());
        record.setGiftId(livesGift.getId());
        record.setGiftIcon(livesGift.getGiftIcon());
        record.setGiftName(livesGift.getGiftName());

        record.setToAnchorId(anchor.getId());
        record.setToAnchorName(anchor.getAnchorName());

        record.setUserId(Long.valueOf(user.getId()));
        record.setUserName(user.getUserName());

        record.setStatus((byte) 0);
        record.setQuantity(pojo.getQuantity());
        record.setLivesSessionId(pojo.getLivesSessionId());
        record.setLivesRoomId(pojo.getLivesRoomId());
        record.setCreateTime(LocalDateTime.now());

        baseMapper.insert(record);

        //送出奖励
        try {
            boolean isLock = cacheUtils.getLock(FinanceLockPrefix.USER_GIFT_LOCK+user.getId(), CacheUtils.LOCK_WAIT_TIME_60_SECONDS);
            if (isLock){
                this.giftCashback(Long.valueOf(user.getId()));
            }
        }finally{
            //释放锁
            cacheUtils.releaseLock(FinanceLockPrefix.USER_GIFT_LOCK+user.getId());
        }
        //直播的会员
        UserGradeIntegralPOJO userGradeIntegralPOJO=new UserGradeIntegralPOJO();
        userGradeIntegralPOJO.setUserId(Long.valueOf(user.getId()));
        userGradeIntegralPOJO.setGradeIntegral(record.getGiftGold().multiply(new BigDecimal(record.getQuantity())));
        applicationContext.publishEvent(new UserGradeIntegralEvent(userGradeIntegralPOJO));
        return true;
    }

    /**
     * 送出奖励
     * @param userId
     */
    private void giftCashback(Long userId) {
        LambdaQueryWrapper<AnchorLivesGiftRecord> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AnchorLivesGiftRecord::getUserId,userId);
        List<AnchorLivesGiftRecord> list=list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        //礼物总的价格
        BigDecimal totalGoldCoins=list.stream().map(x-> x.getGiftGold().multiply(new BigDecimal(x.getQuantity())).divide(new BigDecimal(100))).reduce(BigDecimal.ZERO, BigDecimal::add);

        //满足条件的充值奖励
        LambdaQueryWrapper<UserRewardConfig> query=new LambdaQueryWrapper<>();
        query.eq(UserRewardConfig::getAwardType,9);
        query.le(UserRewardConfig::getAwardCondition,totalGoldCoins);
        query.orderByDesc(UserRewardConfig::getAwardCondition);
        query.last("limit 1");
        UserRewardConfig rewardConfigs=userRewardConfigService.getOne(query);
        if (null != rewardConfigs){
            LambdaQueryWrapper<UserRewardHistory> rewardHistoryQuery=new LambdaQueryWrapper<>();
            rewardHistoryQuery.eq(UserRewardHistory::getUserId,userId);
            rewardHistoryQuery.eq(UserRewardHistory::getType, AccountBusinessTypeEnum.USER_SEND_OUT_GIFT_RETURN_COST.getType());
            rewardHistoryQuery.eq(UserRewardHistory::getCorrespondingId,rewardConfigs.getConId());
            List<UserRewardHistory> result = userRewardHistoryService.list(rewardHistoryQuery);
            if (CollectionUtils.isNotEmpty(result)){
                return;
            }
            BigDecimal refundAmount =new BigDecimal(rewardConfigs.getAwardCondition()).multiply(rewardConfigs.getAwardUnit()).divide(new BigDecimal(100));
            userService.transferAccounts(userId, AccountBusinessTypeEnum.USER_SEND_OUT_GIFT_RETURN_COST,refundAmount,rewardConfigs.getConId());
        }
    }
}
